package com.hsomandroidapp.base;

import android.content.Context;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.ImageView;

import com.hsomandroidapp.cache.ImageCache;
import com.hsomandroidapp.http.HsomHttpClient;
import com.hsomandroidapp.util.StringUtils;
import com.hsomandroidapp.util.Utils;

public class ImageLoadTask extends AsyncTask<Void, Void, Bitmap> {
	private static final String TAG = "ImageLoadTask";
	private Bitmap bitmap = null;
	private ImageView imageView;
	private String url;
	private ImageCache imageCache;
	private Context context;

	public ImageLoadTask(ImageView paramImageView, String paramString,Context context) {
		this.imageView = paramImageView;
		this.url = paramString;
		this.imageCache = ImageCache.getInstance(paramImageView.getContext());
		if (!StringUtils.isEmpty(this.url)) {
			Bitmap bmp = this.imageCache.get(this.url);
			if (null != bmp) {
				this.bitmap = bmp;
			}
		}
		this.context = context;
	}

	@Override
	protected Bitmap doInBackground(Void... arg0) {
		if (null != this.bitmap)
			return this.bitmap;
		else {
			try {
				HsomHttpClient client =  new HsomHttpClient();
				APNType apnType = APN.getApnType(context);
				client.setHttpProxy(apnType.getProxy(), apnType.getPort());
				byte[] data = client.getImage(this.url);
				if(null != data && data.length >0){
					this.bitmap = Utils.getBitmapAutoResize(data);
					this.imageCache.put(this.url, this.bitmap);
				}
			
			} catch (Exception e) {
				Log.e(TAG, e.toString());
			}

		}
		return this.bitmap;
	}
	

	@Override
	protected void onPostExecute(Bitmap paramBitmap) {
		super.onPostExecute(paramBitmap);
		if (paramBitmap != null){
			this.imageView.setImageBitmap(paramBitmap);
		}
	}
	
	@Override
	protected void onPreExecute() {
	}


}
